package com.zhucai.credit.bank.service.impl;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhucai.credit.bank.bean.BankTransfer;
import com.zhucai.credit.bank.ccbe.bean.PlatformReceive;
import com.zhucai.credit.bank.ccbe.service.CcbeService;
import com.zhucai.credit.bank.service.IFactoringService;
import com.zhucai.credit.bean.CreditRecord;
import com.zhucai.credit.common.CommonEnums.CrAprovalStatus;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.model.CreditApplicationEntity;
import com.zhucai.credit.model.CreditRecordEntrity;
import com.zhucai.credit.monitor.service.INotificationService;
import com.zhucai.credit.repository.CreditApplicationRepository;
import com.zhucai.credit.repository.CreditRecordRepository;
import com.zhucai.credit.service.impl.problem.ProblemSericeImpl;
import com.zhucai.credit.utils.TimeUtils;


@Service("E_POINT")
public class CcbEPointServiceImpl implements IFactoringService {
	private static final Logger logger = LoggerFactory.getLogger(CcbEPointServiceImpl.class);
	
	@Autowired
	ProblemSericeImpl problemSericeImpl;
	@Autowired
	CreditRecordRepository creditRecordRepository;
	@Autowired
	CreditApplicationRepository creditApplicationRepository;
	@Autowired
	CcbeService ccbeService;
	@Resource(name = "EMAIL")
	private INotificationService emailINotificationService;
	
	@Override
	public CreditRecord preHandle(BankTransfer creditRecord) {

		return creditRecord;
	}

	/*
	       供应商审核通过的融资计划到建行审核
	       平台账款新增信息接收 6W5574
	   @return 
	   @date 2017年11月29日 @user hsg
	 */
	@Override
	public CreditRecord apply(BankTransfer cr) {
		logger.info("### creditRecordToCCb 供应商审核通过的融资计划到建行审核 start");
		 //调用建行接口6W5574
		 String fail_reason="";
		 CreditRecord creditRecord = new CreditRecord();
		 try {
				 CreditRecordEntrity cre = creditRecordRepository.findByTidAndStatusNot(cr.getTid(), HelpConstant.Status.delete);
				 if(cre==null){
					 /**
					  * 问题记录
					  */
					String problem = "### creditRecordToCCb方法失败  recordNo="+ cr.getRecordNo()+"查询融资记录为空";
					problemSericeImpl.setProblem(problem,"6W5574");
					
					fail_reason="确认融资失败:融资数据异常！！";
					
					logger.info("### creditRecordToCCb recordNo={}, 供应商审核通过的融资计划到建行审核  查询融资记录为空  ",cr.getRecordNo());
					
					emailINotificationService.notification(problem);
					
					creditRecord.setReturnMessage(fail_reason);
					return creditRecord;
				 }
				//查询最近的有效的报名信息
				 CreditApplicationEntity cae = creditApplicationRepository.findCoopInfo(HelpConstant.Status.delete,cre.getParticipator(),cre.getOriginator(),CrAprovalStatus.BANK_SUCCESS.toString(),cre.getCrProdId());
				 //判断融资表里的建行合同编号和报名编号是否是最新的 2018-09-11
				 if(cae == null){
					 logger.error("### CCB发送5574时查询最新的报名信息时 最新的报名信息为 null,融资单号={}",cre.getRecordNo());
					 
					 /**
					  * 问题记录
					  */
					String problem = "### creditRecordToCCb方法失败  recordNo="+ cr.getRecordNo()+"查询最新的报名信息为空";
					problemSericeImpl.setProblem(problem,"6W5574");
					
					 return creditRecord;
				 }
				 //当融资单里的报名编号不是最新的，更新融资单里的最新的报名编号
				 if(!cae.getAppNum().equals(cre.getAppNum())){
					 creditRecordRepository.updateAppNum(cre.getTid(),cae.getAppNum(),cae.getContractNum());
				 }
				 
				 PlatformReceive platformReceive = new PlatformReceive();
				 platformReceive.setBill_balance_amt(String.valueOf(cre.getCreditGetAmount()));
				 /**
				  * 2018-05-28  发票日期修改为当前日期
				  */
				 platformReceive.setBill_date(TimeUtils.changeDate2(new Date()));
				 platformReceive.setBill_num(cre.getInvoiceNoCode());
				 platformReceive.setContract_num(cae.getContractNum());
				 platformReceive.setRelate_cust_name(cae.getApplicantEnterpriseName());
				 /**
				  * 2018-06-04 修改账期为账款到期日和当天的差值
				  */
				 Integer dateTian = TimeUtils.dateTian(cre.getLoanDate(), new Date());
				 platformReceive.setCredit_period(dateTian);
				 platformReceive.setCust_orgn_code(cre.getParticipatorOrgnCode());
				 platformReceive.setR_cust_orgn_code(cre.getOriginatorOrgnCode());
				 platformReceive.setRequest_orgn_num(HelpConstant.CurrencyFile.zhucai_num);
				 List<PlatformReceive> parmList=new ArrayList<PlatformReceive>();
				 parmList.add(platformReceive);
				 Map<String, String> rsMap = ccbeService.platformReceive(parmList);
				 String rsStatus=rsMap.get("receive_state");
				 
				 if(rsStatus!=null&&rsStatus.equals("1")){
					 creditRecord.setReturnStatus("OK");
					 logger.info("### creditRecordToCCb recordNo={}, 供应商审核通过的融资计划到建行审核  成功  ",cr.getRecordNo());
				 }else{
					creditRecord.setReturnStatus("FAIL");
					fail_reason=rsMap.get("fail_reason");
					creditRecord.setReturnMessage(fail_reason);
					// 问题记录
					String problem = "recordNo="+ cre.getRecordNo()+"调用建行接口失败,6W5574 errorMsg="+fail_reason;
					problemSericeImpl.setProblem(problem,"6W5574");
					
					logger.info("### creditRecordToCCb recordNo={}, 供应商审核通过的融资计划到建行审核  失败 ，err={}",cr.getRecordNo(),rsMap.get("fail_reason"));
				 }
		} catch (SocketException e) {
			creditRecord.setReturnStatus("FAIL");
			fail_reason="连接超时,请稍后再试!";
			creditRecord.setReturnMessage(fail_reason);
			return creditRecord;
		}  catch (Exception e) {
			creditRecord.setReturnStatus("FAIL");
			fail_reason="网络异常!";
			// 问题记录
			String problem = "### creditRecordToCCb 供应商审核通过的融资计划到建行审核 异常  recordNo="+ cr.getRecordNo()+"err="+e;
			problemSericeImpl.setProblem(problem,"6W5574");
			
			logger.info("### creditRecordToCCb recordNo={}, 供应商审核通过的融资计划到建行审核  失败,err={}",cr.getRecordNo(),e);
			emailINotificationService.notification("### 建行提交5574异常 record="+cr.getRecordNo()+"err="+e);
			return creditRecord;
		}
		return creditRecord;
	}

	@Override
	public CreditRecord draw(BankTransfer creditRecord) {
		
		throw new UnsupportedOperationException("建行E点通不支持平台支取操作");
	}

	@Override
	public CreditRecord pay(BankTransfer creditRecord) {
		
		throw new UnsupportedOperationException("建行E点通不支持平台还款操作");
	}

}
